#include "../head/server.h"

/* // 得到绝对路径
void getAbsolutePath(char *path)
{
	char *token;
	char *rest = path;
	char result[100]; // 使用临时缓冲区存储结果路径
	result[0] = '\0'; // 初始化结果路径为空

	while ((token = strtok_r(rest, "/", &rest)))
	{
		if (strcmp(token, "..") == 0)
		{
			// 如果当前token是"..", 则回退到上一级目录
			char *prevToken = strrchr(result, '/');
			if (prevToken)
			{
				*prevToken = '\0'; // 截断到上一级目录
			}
		}
		else if (strcmp(token, ".") != 0)
		{
			// 如果当前token不是"."，则将其添加到结果路径中
			strcat(result, "/");
			strcat(result, token);
		}
	}

	// 将最终结果复制回原始路径
	strcpy(path, result);
} */

// 查询path是否在表中
/* int is_path(MYSQL *mysql, char *path)
{
	char sql[1024] = {0};
	sprintf(sql, "select count(*) from all_user_file where file_path = '%s';", path);
	puts(sql);
	int qret = mysql_query(mysql, sql);
	if (qret != 0)
	{
		fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
		return 0;
	}
	MYSQL_RES *res = mysql_store_result(mysql);
	if (res == NULL)
	{
		fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
		mysql_free_result(res);
		return 0;
	}
	MYSQL_ROW row = mysql_fetch_row(res);
	if (row == NULL)
	{
		fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
		mysql_free_result(res);
		return 0;
	}
	// int res = atoi(row[0]);
	mysql_free_result(res);

	return atoi(row[0]);
}
 */
int cd_work(int net_fd, char *username, MYSQL *mysql)
{
	train_t train;
	bzero(&train, sizeof(train));
	recv(net_fd, &train.length, sizeof(train.length), MSG_WAITALL);
	recv(net_fd, train.data, train.length, MSG_WAITALL);

	// 用户输入的任意路径
	char path[1024] = {0};
	memcpy(path, train.data, train.length);
	// puts(path);

	// 从数据库中拿到当前路径
	char *cur_path = get_current_path_by_username(mysql, username);

	// 获取绝对路径
	char absolutePath[1024] = {0};
	if (!memcmp(path, "/", strlen("/")))
	{
		memcpy(absolutePath, path, strlen(path));
	}
	else
	{
		memcpy(absolutePath, cur_path, strlen(cur_path));
		strcat(absolutePath, "/");
		strcat(absolutePath, path);
	}
	getAbsolutePath(absolutePath);
	puts(absolutePath);

	if (is_path(mysql, absolutePath))
	{
		bzero(&train, sizeof(train));
		train.length = strlen("success");
		memcpy(train.data, "success", train.length);
		send(net_fd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);

		// 更新user_info中该username的current_path字段
		char sql[1024] = {0};
		sprintf(sql, "update user_info set current_path = '%s' where username = '%s';", absolutePath, username);
		int qret = mysql_query(mysql, sql);
		if (qret != 0)
		{
			fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
			return 0;
		}
		puts(sql);
	}
	else
	{
		bzero(&train, sizeof(train));
		train.length = strlen("fail");
		memcpy(train.data, "fail", train.length);
		send(net_fd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
	}

	// 释放内存
	free(cur_path);
	return 0;
}